package com.ocom.payhandle.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.pay.EntityXfRecordProcessExtend;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.callpackage.AddPackagePayRequest;
import com.ocom.common.request.payhandle.*;
import com.ocom.common.request.xfrecde.XfOrderVerificationRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.GzhParamVo;
import com.ocom.common.vo.payconfig.kitchenprinter.PlanKitchenPrinterRequest;
import com.ocom.common.vo.pyhandle.GetPointMealVo;
import com.ocom.common.vo.pyhandle.MealOrderListVo;
import com.ocom.common.vo.pyhandle.OrderMealListVo;
import com.ocom.payhandle.feign.PayConfigClientService;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.fun.PayFunService;
import com.ocom.payhandle.fun.PayHandleFunService;
import com.ocom.payhandle.mq.business.saveorder.SaveOrderProductService;
import com.ocom.payhandle.service.*;
import com.ocom.payhandle.vo.DeviceInfoVo;
import com.ocom.payhandle.vo.MqSaveOrderVo;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * 机器点餐
 */
@Slf4j
@RestController
public class MachDishesController {

    @Autowired
    PayHandleFunService payHandleFunService;

    @Autowired
    PayFunService payFunService;

    @Autowired
    DeviceInfoService deviceInfoService;

    @Autowired
    XfPointInfoService xfPointInfoService;

    @Autowired
    private XfMerchantInfoService xfMerchantInfoService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private ConsTypeConfigService consTypeConfigService;

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    private XfGoodsListProcessService xfGoodsListProcessService;

    @Autowired
    private XfCardInfoService xfCardInfoService;


    @Autowired
    private XfMealTimeService xfMealTimeService;

    @Autowired
    private SaveOrderProductService saveOrderProductService;

    @Autowired
    private XfRecordFeign xfRecordFeign;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private PayConfigClientService payConfigClientService;

    @Autowired
    private XfSubAccountListService xfSubAccountListService;


    @Autowired
    private XfDiscountConfigServcie xfDiscountConfigServcie;

    @Autowired
    private XfRecordProcessExtendService xfRecordProcessExtendService;

    @Autowired
    XfRecordProcessExxxService xfRecordProcessExxxService;

    @Value("${pay.url}")
    private String payUrl;

    @Autowired
    private CompanyInfoService companyInfoService;

    @PostMapping(PayHandleUrl.URL_getPointMeal)
    public Result getPointMeal(@RequestBody GetPointMealRequest request) {
        EntityXfDeviceInfo entityXfDeviceInfo = deviceInfoService.GetDeviceInfo(request.getCompanyId(), request.getMachNo());
        if (entityXfDeviceInfo == null) {
            return ResultUtil.error(ResultEnum.Err_2013);
        }
        GetPointMealVo getPointMealVo = new GetPointMealVo();
        getPointMealVo.setPointId(entityXfDeviceInfo.getPointId());
        if (getPointMealVo.getPointId() == null) {
            getPointMealVo.setPointId(0);
        }
        getPointMealVo.setMealDate(DateUtil.getDate());
        getPointMealVo.setMealNo(0);
        if (entityXfDeviceInfo.getConsType() == 1) {
            getPointMealVo.setMealNo(payHandleFunService.selectMealNo(request.getCompanyId(), entityXfDeviceInfo.getPointId().longValue(),0, new Date()));
        }
        if (getPointMealVo.getMealNo() == null) {
            getPointMealVo.setMealNo(0);
        }
        return ResultUtil.success(getPointMealVo);
    }

    /**
     * 业务逻辑：
     * 1、从设备信息表xf_device_info找到com_id ，device_no匹配的记录deviceInfo。
     * select 	point_id as pointId , consume_type
     * from 	xf_device_info
     * where 	com_id = @companyId	and 	device_no = @machNo
     * order by	create_time 	desc 	limit 	1
     * <p>
     * 2、如果deviceInfo. consume_type == 1，调用3.5计算消费餐段mealNo，否则mealNo:=0
     */


    //点餐主扫支付
    @PostMapping(PayHandleUrl.URL_PayHandle_orderDishesPay)
    public Result orderDishesPay(@RequestBody OrderDishesPayRequest request) {
        log.info("订餐参数 【{}】 g8j4kx9g ",request);
        if(request.getMealNo() == null ) request.setMealNo(0);
        String machno = "";
        String tradeNo = "";
        try {
            machno = request.getMachNo();
            if (StringUtils.isNumeric(request.getMachNo())) {
                machno = request.getMachNo();
            } else {
                machno = "00000000";
            }

            Long companyID = request.getComId();
            //向redis分布式锁插入订单号是否重复
            //向redis分布式锁插入订单号是否重复
            tradeNo = request.getTradeNo();
            String tradeNoRedis = "orderDishesPay:" + companyID + ":" + machno + ":" + tradeNo;
            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
                log.info("请求方式:【{} y1zpp8zf 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（主扫）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
            entityXfRecordProcess.setDeviceName("点餐订餐");
            entityXfRecordProcess.setOpType(12l);//小程序点餐
            entityXfRecordProcess.setOpTypeDiff(201l);
            if(request.getType()==2){
                entityXfRecordProcess.setOpTypeDiff(204l);
            }
            if(request.getType()==9){
                entityXfRecordProcess.setOpTypeDiff(306l);
            }
            entityXfRecordProcess.setConsType(request.getConsType());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPlatOrderNo(request.getTradeNo());
            //判断消费时间段
            Date date = new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
            //查询收费的和商家信息
            //		relatedDevice(entityXfRecordProcess, request.getComId(), request.getMachNo(), date);

            entityXfRecordProcess.setComId(companyID);
            entityXfRecordProcess.setPointId(request.getPointId().longValue());
            entityXfRecordProcess.setMerchId(0l);
            entityXfRecordProcess.setMerchName("本单位");
            //有消费点
            if (request.getPointId() > 0l) {
                EntityXfPointInfo entityXfPointInfo = xfPointInfoService.getTollPointInfo(companyID, request.getPointId());
                if (entityXfPointInfo != null) {
                    entityXfRecordProcess.setPointName(entityXfPointInfo.getPointName());

                    if (entityXfPointInfo.getMerchId() != 0) {
                        EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.getMerchInfo(entityXfPointInfo.getComId(), entityXfPointInfo.getMerchId());
                        entityXfRecordProcess.setMerchId(entityXfPointInfo.getMerchId().longValue());
                        entityXfRecordProcess.setMerchName(entityXfMerchantInfo.getMerchName());
                    }
                }
            } else {
                entityXfRecordProcess.setPointName("本单位");
            }

            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getComId(), request.getPId());
            EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getComId(), request.getPId());
            entityXfRecordProcess.setComId(request.getComId());
            entityXfRecordProcess.setDeviceNo(machno);
            entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
            entityXfRecordProcess.setAccTypeId(entityXfAccountInfo.getAccTypeId());
            entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
            entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
            entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
            //查询个人所在的组织
            entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
            if (entityPersonnelInfo.getDeptId() == null || entityPersonnelInfo.getDeptId() == 0l) {
                entityPersonnelInfo.setDeptId(0l);
            } else {
                EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getComId(), entityPersonnelInfo.getDeptId());
                if (entityDeptInfo != null) {
                    entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
                }
            }

            //计算金额
            int consMoney = -1 * Math.abs(request.getAmount());
            entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));

            Integer intMealNo = 0;
            if (request.getMealNo() != null) {
                intMealNo = request.getMealNo();
            }
            entityXfRecordProcess.setMealNo(String.valueOf(request.getMealNo()));
            entityXfRecordProcess.setMealDate(DateUtils.strToDate2(request.getMealDate()));
            int discount = xfDiscountConfigServcie.selectSiscount(request.getComId(), entityXfAccountInfo.getPId(),
                    entityXfAccountInfo.getAccTypeId(), request.getConsType(), entityXfRecordProcess.getMealDate(), intMealNo, request.getAmount(), entityXfRecordProcess);
//            int discount = 0;
//            int realMoney = consMoney + discount;
            consMoney = entityXfRecordProcess.getConsMoney().intValue();
            int realMoney = consMoney + discount;
            if (request.getReceiptPrice() != 0) {
                realMoney -= Math.abs(request.getReceiptPrice());
            }

            //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setDiscount(Long.valueOf(discount));
            entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
            entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));
            //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
            entityXfRecordProcess.setConsState(request.getConsState());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPayWay(request.getPayWay());
            entityXfRecordProcess.setConsTime(new Date());
            entityXfRecordProcess.setReserved3(request.getRemark());
            entityXfRecordProcess.setReceiptId(request.getReceiptId());
            entityXfRecordProcess.setReceiptName(request.getReceiptName());

            //查询扣款顺序
            EntityConsTypeConfig entityConsTypeConfig = consTypeConfigService.selectEntityConsTypeConfig(companyID, request.getConsType());
            EntityXfSubAccountList entityXfSubAccountList = null;
            Integer accountId = entityXfAccountInfo.getId();
            if (entityConsTypeConfig.getSubAccount() > 0) {
                entityXfSubAccountList = xfSubAccountListService.getUserSubAccount(
                        entityXfRecordProcess.getComId(),
                        entityXfRecordProcess.getPId(),
                        entityConsTypeConfig.getSubAccount()
                );
                accountId = entityXfSubAccountList.getId();
            }
            if (request.getType() == 7 || realMoney == 0) {
                getWallet(entityXfRecordProcess, entityConsTypeConfig, entityXfAccountInfo, entityXfSubAccountList);
                entityXfRecordProcess.setOpTypeDiff(100l);
            }


            payHandleFunService.relatedReceiptNo(entityXfRecordProcess);


            //693单位特殊处理  分院仅消费一次 2025年8月1日14:59:05
            try {
                if (request.getComId() == 693l && entityXfRecordProcess.getPointId() == 1044l) {
                    int sun = xfRecordProcessExxxService.getUserPartCityCount(693l, entityXfRecordProcess.getMealDate(), entityXfRecordProcess.getPId());
                    if (sun > 0) {
                        return ResultUtil.error(ResultEnum.Err_3119);
                    }
                }
            } catch (Exception e) {
                log.error("厦门第一医院分院仅消费一次-异常  sjObbk6X 【{}】", e);
            }


            //代扣 延迟付款的处理
            if(request.getType()==9 && request.getDelayPay()){
                entityXfRecordProcess.setPayState(-11);
                entityXfRecordProcess.setConsState(205);

                List<EntityXfMealTime> entityXfMealTimes = xfMealTimeService.selectTimeList3(request.getComId(),entityXfRecordProcess.getPointId(),entityXfRecordProcess.getAccTypeId());
                for (EntityXfMealTime entityXfMealTime:entityXfMealTimes){
                    if(entityXfMealTime.getMealNo().equals(request.getMealNo().toString())){
                        String pDate = request.getMealDate()+" "+entityXfMealTime.getBeginTime();
                        Date nDate = DateUtils.strToDate(pDate);
                        entityXfRecordProcess.setConsTime(nDate);
                        entityXfRecordProcess.setCreateTime(nDate);
                        break;
                    }
                }

                entityXfRecordProcess.setReserved3("实际支付时间:"+DateUtil.getDateTime());
            }

            try {
                int i = xfRecordProcessService.insertEntityXfRecord(companyID, entityXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式:【{} o1eyyh27 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }

                EntityXfRecordProcessExtend entityXfRecordProcessExtend =new EntityXfRecordProcessExtend();
                entityXfRecordProcessExtend.setComId(companyID);
                entityXfRecordProcessExtend.setOrderNo(entityXfRecordProcess.getOrderNo());
                entityXfRecordProcessExtend.setOrderId(entityXfRecordProcess.getId());
                entityXfRecordProcessExtend.setCancelState(0);
                entityXfRecordProcessExtend.setReceiptPrice(-1*Math.abs(request.getReceiptPrice()));
                boolean j = xfRecordProcessExtendService.insertEntityXfRecordExtend(companyID, entityXfRecordProcessExtend);
                if (!j) {
                    log.info("请求方式:【{} yhzntn4l 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }

            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{} gy6xbtgk 】,机器号:【{}】,入库新增等待表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式:【{} s87wcnr5 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            //保存菜品 2023年5月23日13:52:16
            try {
                if (request.getDishesInfo() != null && request.getDishesInfo().size() > 0) {
                    List<EntityXfGoodsListProcess> entityXfGoodsListProcesses = new ArrayList<>();
                    if (entityXfRecordProcess.getMerchId() == null) entityXfRecordProcess.setMerchId(0l);
                    if (entityXfRecordProcess.getDeptId() == null) entityXfRecordProcess.setDeptId(0l);
                    if (entityXfRecordProcess.getPId() == null) entityXfRecordProcess.setPId(0l);
                    for (DishesInfoVo dishesInfoVo : request.getDishesInfo()) {
                        EntityXfGoodsListProcess entityXfGoodsListProcess = new EntityXfGoodsListProcess();
                        entityXfGoodsListProcess.setComId(request.getComId());
                        entityXfGoodsListProcess.setDeviceNo(entityXfRecordProcess.getDeviceNo());
                        entityXfGoodsListProcess.setPointId(entityXfRecordProcess.getPointId().intValue());
                        entityXfGoodsListProcess.setMerchId(entityXfRecordProcess.getMerchId().intValue());
                        entityXfGoodsListProcess.setPId(entityXfRecordProcess.getPId().longValue());
                        entityXfGoodsListProcess.setDeptId(entityXfRecordProcess.getDeptId().intValue());
                        entityXfGoodsListProcess.setReceiptId(request.getReceiptId());
                        entityXfGoodsListProcess.setReceiptName(request.getReceiptName());
                        entityXfGoodsListProcess.setOrderNo(entityXfRecordProcess.getOrderNo());

                        entityXfGoodsListProcess.setConsTime(entityXfRecordProcess.getConsTime());
                        entityXfGoodsListProcess.setMealDate(entityXfRecordProcess.getMealDate());
                        entityXfGoodsListProcess.setMealNo(request.getMealNo());
                        entityXfGoodsListProcess.setConsType(request.getConsType());
                        entityXfGoodsListProcess.setIfRefund(0);
                        entityXfGoodsListProcess.setDishesId(dishesInfoVo.getDishesId());
                        entityXfGoodsListProcess.setDishesName(dishesInfoVo.getDishesName());
                        entityXfGoodsListProcess.setPriceMode(dishesInfoVo.getPriceMode());
                        entityXfGoodsListProcess.setWeightNumber(dishesInfoVo.getWeightNumber());
                        entityXfGoodsListProcess.setDishesPrice(dishesInfoVo.getDishesPrice());
                        entityXfGoodsListProcess.setUnitPrice(dishesInfoVo.getUnitPrice());
                        entityXfGoodsListProcess.setMonthValue(entityXfRecordProcess.getMonthValue());
                        entityXfGoodsListProcess.setCreateTime(new Date());

                        entityXfGoodsListProcesses.add(entityXfGoodsListProcess);
                    }
                    xfGoodsListProcessService.addXfGoodsListProcessList(request.getComId(), entityXfGoodsListProcesses);
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{} dxle22ot 】,机器号:【{}】,入库菜品缓存表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式:【{} mn4ct82b 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_900));
            }

            //查询配置信息向统一平台发起支付
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = payHandleFunService.configure(entityXfRecordProcess);

            if(request.getType() != 7){

                if (entiyXfMerchPayInfo == null) {
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }

                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                updateXfRecordProcess.setId(entityXfRecordProcess.getId());
                updateXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
                try {
                    int i = xfRecordProcessService.updateEntityXfRecord(companyID, updateXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式:【{} lst1g20i 】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "支付请求（主扫）", machno, updateXfRecordProcess, "等待表修改入库失败");
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式:【{} 3oae36m8 】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（主扫）", machno, updateXfRecordProcess, e, ste.getLineNumber());
                }
            }

            HashMap<Object, Object> map = new HashMap<>();
            map.put("totalFee", Math.abs(realMoney));

            if (request.getType() == 9) {
                if(request.getDelayPay()){
                    try {
                        MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                        mqSaveOrderVo.setComId(request.getComId());
                        mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                        mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                        mqSaveOrderVo.setType(2);
                        saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式:【{} 9qt889im 】,机器号:【{}】,代扣-插成功库:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    }
                    map.put("type", 9);
                    map.put("result", "success");
                    map.put("message", "预付成功");
                    return ResultUtil.success(map);
                }else{
                    QrCardPayRequest qrCardPayRequest =new QrCardPayRequest();
                    qrCardPayRequest.setCompanyId(request.getComId());
                    qrCardPayRequest.setMachNo(entityXfRecordProcess.getDeviceNo());
                    qrCardPayRequest.setTradeNo(entityXfRecordProcess.getOrderNo());
                    qrCardPayRequest.setAmount(entityXfRecordProcess.getRealMoney().intValue());
                    qrCardPayRequest.setConsType(entityXfRecordProcess.getConsType());
                    qrCardPayRequest.setConsState(entityXfRecordProcess.getConsState());
                    qrCardPayRequest.setType(1);

                    JSONObject jsonObject =new JSONObject();
                    int payState = payFunService.withholding(entityXfRecordProcess,qrCardPayRequest,null,jsonObject,2);

                    if (payState == 2) {
                        //支付失败
                        return ResultUtil.info(4024, jsonObject.getString("msg"));
                    }

                    if (payState == 1) {
                        map.put("type", 9);
                        map.put("result", "success");
                        map.put("message", "支付成功");
                        return ResultUtil.success(map);
                    } else if (payState == -1) {
                        //商户支付渠道未配置"
                        return ResultUtil.error(ResultEnum.Err_3048);
                    } else if (payState == -2) {
                        //代扣未签约"
                        return ResultUtil.error(ResultEnum.Err_3047);
                    } else if (payState == -11) {
                        //订单号重复
                        return ResultUtil.error(ResultEnum.Err_802);
                    } else if (payState == -12) {
                        //余额不足
                        return ResultUtil.error(ResultEnum.Err_4024);
                    } else {
                        //支付结果未知
                        return ResultUtil.error(ResultEnum.Err_3029);
                    }
                }
            }else if (request.getType() == 7 || realMoney == 0) {
                //钱包
                try {
                    Boolean bo = xfRecordProcessService.saveLxOrder2(entityXfRecordProcess.getComId(), entityXfRecordProcess, entityConsTypeConfig.getSubAccount(), accountId);
                    if (!bo) {
                        return ResultUtil.error(ResultEnum.Err_4069);
                    }

                    Boolean aBoolean = xfGoodsListProcessService.saveXfGoodsListRecode(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrderNo());

                    //新增成功表的退款数据
//                    Date payTime = new Date();
//                    entityXfRecordProcess.setPayTime(payTime);
//                    entityXfRecordProcess.setPayState(1);
//
//                    Result sveResult = xfRecordFeign.sveXfRecord(entityXfRecordProcess);

                    try {
                        MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                        mqSaveOrderVo.setComId(request.getComId());
                        mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                        mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                        mqSaveOrderVo.setType(1);
                        saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式:【{} tiep77jd 】,机器号:【{}】,代扣-插成功库:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    }

                    log.info("迁移订餐结果到成功表 【{}】【{}】", entityXfRecordProcess.getOrderNo(), aBoolean);

                    map.put("type", 7);
                    map.put("result", "success");
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("订餐异常 【{}】", request);
                    return ResultUtil.error(ResultEnum.Err_3030);
                }

                try {
                    log.info("开始打印订单 订单：【{}】", entityXfRecordProcess);
                    PlanKitchenPrinterRequest planKitchenPrinterRequest = new PlanKitchenPrinterRequest();
                    planKitchenPrinterRequest.setComId(entityXfRecordProcess.getComId());
                    planKitchenPrinterRequest.setPointId(entityXfRecordProcess.getPointId());
                    planKitchenPrinterRequest.setOrderNo(entityXfRecordProcess.getOrderNo());
                    planKitchenPrinterRequest.setCheckPrint(true);

                    log.info("开始打印订单 planKitchenPrinter：【{}】", planKitchenPrinterRequest);
                    Result printResult = payConfigClientService.planKitchenPrinter(planKitchenPrinterRequest);
                    log.info("订单打印结果【{}】", printResult);
                } catch (Exception e) {
                    //e.printStackTrace();
                    log.info("订单打印异常 【{}】【{}】", entityXfRecordProcess, e);
                }

                return ResultUtil.success(map);
            } else {

                //if opTypeDiff  == 201
                String payUrl = companyInfoService.getPayCenterUrl(companyID,entiyXfMerchPayInfo.getCompanyId());
                String RealUrl = payUrl + "/unifiedpreorder/lordesau.do";

                Map<String, Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                stringObjectMap.put("password", entiyXfMerchPayInfo.getPassword());
                stringObjectMap.put("user_name", entiyXfMerchPayInfo.getUserName());

                stringObjectMap.put("pos_no", machno);
                stringObjectMap.put("devsnip", "127.0.0.1");
                stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                stringObjectMap.put("subject", "公众号订餐");
                stringObjectMap.put("total_amount", Math.abs(realMoney));
                stringObjectMap.put("fee_type", "CNY");
                stringObjectMap.put("trade_type", "JSAPI");
                stringObjectMap.put("payway", 3);
                stringObjectMap.put("body", request.getComId().toString());
                stringObjectMap.put("operator", "admin");
                stringObjectMap.put("openid", request.getOpenId());

                //type  1微信官方  3 随行付微信  2建行
                if (request.getType() == 2) {
                    stringObjectMap.put("trade_type", "MWEB");
                    stringObjectMap.put("pay_way", 15);
                    stringObjectMap.put("payway", 15);
                }

                RequestUtil requestUtil = new RequestUtil();

                log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

                Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

                Gson gson = new Gson();
                Result result3 = gson.fromJson(gson.toJson(re), Result.class);

                log.info("公众号返回【{}】  ", result3);

                if (result3 == null || result3.getCode() != 200) {
                    return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
                }

                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));

                GzhParamVo gzhParamVo = GzhParamFormat.formate(jsonObject, request.getType());
                log.info("公众号参数【{} 1r608see 】 【{}】【{}】", request, entityXfRecordProcess.getPlatOrderNo(), gzhParamVo);
                return ResultUtil.success(gzhParamVo);
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{} udwzvw37 】,机器号:【{}】,请求参数:【{}】,异常1:【{}】,行号:【{}】", "支付请求（主扫）", machno, request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }


    @PostMapping(PayHandleUrl.URL_PayHandle_orderDishesPay3)
    public Result orderDishesPay3(@RequestBody OrderAddPackagePayRequest request) {

        String machno = "";
        String tradeNo = "";
        try {
            if (StringUtils.isNumeric(request.getMachNo())) {
                machno = request.getMachNo();
            } else {
                machno = "00000000";
            }
            Long companyID = request.getComId();
            //向redis分布式锁插入订单号是否重复
            tradeNo = request.getTradeNo();
            String tradeNoRedis = "orderDishesPay:" + companyID + ":" + machno + ":" + tradeNo;
            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
                log.info("请求方式:【{} hc4aq9ig 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（主扫）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
            entityXfRecordProcess.setDeviceName("视频话机");
            entityXfRecordProcess.setOpType(12l);
            entityXfRecordProcess.setOpTypeDiff(201l);
            entityXfRecordProcess.setConsType(request.getConsType());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPlatOrderNo(request.getTradeNo());
            //判断消费时间段
            Date date = new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));

            //查询收费的和商家信息
//            payHandleFunService.relatedDevice(entityXfRecordProcess, request.getComId(), request.getMachNo(), date);

            entityXfRecordProcess.setComId(companyID);
            entityXfRecordProcess.setPointId(request.getPointId().longValue());
            entityXfRecordProcess.setMerchId(0l);
            entityXfRecordProcess.setMerchName("本单位");

            if (null != request.getMerchId() && request.getMerchId() != 0) {
                EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.getMerchInfo(request.getComId(), request.getMerchId());
                entityXfRecordProcess.setMerchId(request.getMerchId().longValue());
                entityXfRecordProcess.setMerchName(entityXfMerchantInfo.getMerchName());
            }
            //有消费点
//            if (request.getPointId() > 0l) {
//                EntityXfPointInfo entityXfPointInfo = xfPointInfoService.getTollPointInfo(companyID, request.getPointId());
//                if (entityXfPointInfo != null) {
//                    entityXfRecordProcess.setPointName(entityXfPointInfo.getPointName());
//
//                    if (entityXfPointInfo.getMerchId() != 0) {
//                        EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.getMerchInfo(entityXfPointInfo.getComId(), entityXfPointInfo.getMerchId());
//                        entityXfRecordProcess.setMerchId(entityXfPointInfo.getMerchId().longValue());
//                        entityXfRecordProcess.setMerchName(entityXfMerchantInfo.getMerchName());
//                    }
//                }
//            } else {
//                entityXfRecordProcess.setPointName("本单位");
//            }

            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getComId(), request.getPId());
            EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getComId(), request.getPId());
            entityXfRecordProcess.setComId(request.getComId());
            entityXfRecordProcess.setDeviceNo(DateUtils.dateTime());
            entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
            entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
            entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
            entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
            //查询个人所在的组织
            entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
            if (entityPersonnelInfo.getDeptId() == null || entityPersonnelInfo.getDeptId() == 0l) {
                entityPersonnelInfo.setDeptId(0l);
            } else {
                EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getComId(), entityPersonnelInfo.getDeptId());
                if (entityDeptInfo != null) {
                    entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
                }
            }

            //计算金额
            int consMoney = -1 * Math.abs(request.getAmount());
            entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));

            Integer intMealNo = 0;
            if (request.getMealNo() != null) {
                intMealNo = request.getMealNo();
            }
//            int discount = xfDiscountConfigServcie.selectSiscount(request.getComId(), entityXfAccountInfo.getPId(),
//                    entityXfAccountInfo.getAccTypeId(), request.getConsType(), date, intMealNo, request.getAmount(), entityXfRecordProcess);
            int discount = 0;
            int realMoney = consMoney + discount;
            //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setDiscount(Long.valueOf(discount));
            entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
            entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));
            //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
            entityXfRecordProcess.setConsState(request.getConsState());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPayWay(request.getPayWay());
            entityXfRecordProcess.setMealNo(String.valueOf(request.getMealNo()));
            entityXfRecordProcess.setConsTime(new Date());

            //视频话机
            entityXfRecordProcess.setReserved1(request.getPackageTypeId().toString());
            entityXfRecordProcess.setMealDate(request.getStartDate());

            //查询扣款顺序
            EntityConsTypeConfig entityConsTypeConfig = consTypeConfigService.selectEntityConsTypeConfig(companyID, request.getConsType());
            EntityXfSubAccountList entityXfSubAccountList = null;
            Integer accountId = entityXfAccountInfo.getId();
            if (null != entityConsTypeConfig && entityConsTypeConfig.getSubAccount() > 0) {
                entityXfSubAccountList = xfSubAccountListService.getUserSubAccount(
                        entityXfRecordProcess.getComId(),
                        entityXfRecordProcess.getPId(),
                        entityConsTypeConfig.getSubAccount()
                );
                accountId = entityXfSubAccountList.getId();
            }
            if (request.getType() == 7) {
                getWallet(entityXfRecordProcess, entityConsTypeConfig, entityXfAccountInfo, entityXfSubAccountList);
            }

            try {
                int i = xfRecordProcessService.insertEntityXfRecord(companyID, entityXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式:【{} 1o3t4j4p 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{} qur3x1fa 】,机器号:【{}】,入库新增等待表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式:【{} ihan1x21 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }

            EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
            updateXfRecordProcess.setId(entityXfRecordProcess.getId());

            //查询配置信息向统一平台发起支付
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = payHandleFunService.selectConfigure(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMerchId());

            if (entiyXfMerchPayInfo == null  && request.getType() != 7) {
                //商户支付渠道未配置"
                return ResultUtil.error(ResultEnum.Err_3048);
            }else{
                if(entiyXfMerchPayInfo != null){
                    updateXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
                }
            }


            try {
                int i = xfRecordProcessService.updateEntityXfRecord(companyID, updateXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式:【{} suvnu77v 】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "支付请求（主扫）", machno, updateXfRecordProcess, "等待表修改入库失败");
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{} c8xk1i7h 】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（主扫）", machno, updateXfRecordProcess, e, ste.getLineNumber());
            }


            Map<String, Object> map = new HashMap<>();
            map.put("totalFee", Math.abs(realMoney));

            if (request.getType() == 7 && request.getPayWay() == 0) {
                //钱包
                try {
                    Boolean bo = xfRecordProcessService.saveLxOrder2(entityXfRecordProcess.getComId(), entityXfRecordProcess, entityConsTypeConfig.getSubAccount(), accountId);
                    if (!bo) {
                        return ResultUtil.error(ResultEnum.Err_4069);
                    }

                    Date mealDate = entityXfRecordProcess.getMealDate();
                    if (null == mealDate) {
                        mealDate = new Date();
                    }
                    AddPackagePayRequest addPackagePayRequest = new AddPackagePayRequest();
                    addPackagePayRequest.setComId(entityXfRecordProcess.getComId());
                    addPackagePayRequest.setPId(entityXfRecordProcess.getPId());
                    addPackagePayRequest.setPackageTypeId(Long.valueOf(entityXfRecordProcess.getReserved1()));
                    addPackagePayRequest.setStartDate(mealDate);
                    Result packagePayResult = payConfigClientService.addPackagePay(addPackagePayRequest);
                    log.info("视频话机发放套餐结果 【{}】【{}】", addPackagePayRequest, packagePayResult);

//                    updateXfRecordProcess.setPayState(1);
//                    updateXfRecordProcess.setPayTime(new Date());
//                    updateXfRecordProcess.setChargeBalance(entityXfAccountInfo1.getAccountRechargeMoney());
//                    updateXfRecordProcess.setSubBalance(entityXfAccountInfo1.getAccountSubsidyMoney());
//                    int i = xfRecordProcessService.updateEntityXfRecord(companyID, updateXfRecordProcess);


                    map.put("type", 7);
                    map.put("result", "success");
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("视频话机发放套餐异常 【{}】", request);
                    return ResultUtil.error(ResultEnum.Err_3030);
                }
            } else {
                String payUrl = companyInfoService.getPayCenterUrl(companyID,entiyXfMerchPayInfo.getCompanyId());
                String RealUrl = payUrl + "/unifiedpreorder/lordesau.do";

                Map<String, Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                stringObjectMap.put("password", entiyXfMerchPayInfo.getPassword());
                stringObjectMap.put("user_name", entiyXfMerchPayInfo.getUserName());

                stringObjectMap.put("pos_no", machno);
                stringObjectMap.put("devsnip", "127.0.0.1");
                stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                stringObjectMap.put("subject", "视频话机套餐购买");
                stringObjectMap.put("total_amount", Math.abs(realMoney));
                stringObjectMap.put("body", request.getComId().toString());
                stringObjectMap.put("operator", "admin");
                stringObjectMap.put("openid", request.getOpenId());

                Gson gson = new Gson();

                //建行公众号
                if (request.getType() == 5) {
                    stringObjectMap.put("fee_type", "CNY");
                    stringObjectMap.put("trade_type", "JSAPI");

                    stringObjectMap.put("payway", 7);
                    stringObjectMap.put("body", request.getComId().toString());
                    stringObjectMap.put("operator", "admin");
                    stringObjectMap.put("openid", request.getOpenId());
//		stringObjectMap.put("notify_url","");

                    RequestUtil requestUtil = new RequestUtil();

                    log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

                    Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

                    Result result3 = gson.fromJson(gson.toJson(re), Result.class);

                    log.info("返回【{}】  ", result3);

                    if (result3 == null || result3.getCode() != 200) {
                        return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
                        /**
                         Map<String,Object> map =new HashMap<>();
                         map.put("outTradeNo","nrFqKJYvQooEtXdTXVKKHVPkkgXxj3Lq");
                         map.put("timeStamp","1657084272");
                         map.put("nonceStr","B7RhLtRQ5XkpLk0h");
                         map.put("appid","wx7b35e13388684b68");
                         map.put("sign","E315466DA8AFD4709DED09A3BB6A0568");
                         map.put("mchId","1483737272");
                         map.put("prepayId","wx06131112573065de8b46e350ebafdc0000");
                         return ResultUtil.success(map);
                         **/
                    }

                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
                    JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));

                    map.put("outTradeNo", jsonObject.getString("out_trade_no"));
                    map.put("timeStamp", jsonObject1.getString("timeStamp"));
                    map.put("nonceStr", jsonObject1.getString("nonceStr"));
                    map.put("appid", jsonObject1.getString("appId"));
                    map.put("sign", jsonObject1.getString("paySign"));
                    map.put("signType", jsonObject1.getString("signType"));
                    String prepayId = jsonObject1.getString("package");
                    if (prepayId != null && prepayId.startsWith("prepay_id=")) {
                        prepayId = prepayId.substring(10);
                    }
                    map.put("prepayId", prepayId);
                    map.put("type", 1);
                }

                //建行H5
                if (request.getType() == 2) {

                    stringObjectMap.put("fee_type", "CNY");
                    stringObjectMap.put("trade_type", "MWEB");
                    stringObjectMap.put("pay_way", 15);
                    stringObjectMap.put("payway", 15);

                    RequestUtil requestUtil = new RequestUtil();

                    log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

                    Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

                    Result result3 = gson.fromJson(gson.toJson(re), Result.class);
                    if (result3.getCode() != 200) {
                        return result3;
                    }
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));

                    map.put("type", 2);
                    map.put("code_url", jsonObject.get("code_url"));
                    log.info("数字人民币返回【{}】  ", map);
                }

                //随行付
                if(request.getType() == 3){
                    //随行付
                    stringObjectMap.put("pos_no", "00000000");
                    stringObjectMap.put("devsnip", "127.0.0.1");
                    stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                    stringObjectMap.put("subject", "小程序点餐");
                    stringObjectMap.put("total_amount", request.getAmount());
                    stringObjectMap.put("fee_type", "CNY");
                    stringObjectMap.put("trade_type", "JSAPI");
                    stringObjectMap.put("payway", 3);
                    stringObjectMap.put("body", request.getComId().toString());
                    stringObjectMap.put("operator", "admin");
                    stringObjectMap.put("openid", request.getOpenId());
//		stringObjectMap.put("notify_url","");

                    RequestUtil requestUtil = new RequestUtil();

                    log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

                    Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

                    Result result3 = gson.fromJson(gson.toJson(re), Result.class);

                    log.info("返回【{}】  ", result3);

                    if (result3 == null || result3.getCode() != 200) {
                        return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
                    }
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
                    JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));

                    map.put("outTradeNo", jsonObject.getString("out_trade_no"));
                    String prepayId = "";

                    map.put("appid", jsonObject.getString("payAppId"));
                    if (jsonObject1 != null) {
                        map.put("timeStamp", jsonObject1.getString("timeStamp"));
                        map.put("nonceStr", jsonObject1.getString("nonce_str"));
                        map.put("appid", jsonObject1.getString("appid"));
                        map.put("sign", jsonObject1.getString("sign"));
                        map.put("mchId", jsonObject1.getString("mch_id"));
                        map.put("signType", jsonObject1.getString("signType"));
                        map.put("mchId", jsonObject1.getString("mch_id"));


                        if (CommonUtil.isNull(jsonObject1.getString("signType"))) {
                            map.put("signType", "MD5");
                        }
                        if (!CommonUtil.isNull(jsonObject1.getString("appid"))) {
                            map.put("appid", jsonObject1.getString("appId"));
                        }
                        if (!CommonUtil.isNull(jsonObject1.getString("nonce_str"))) {
                            map.put("nonceStr", jsonObject1.getString("nonceStr"));
                        }
                        if (!CommonUtil.isNull(jsonObject1.getString("sign"))) {
                            map.put("sign", jsonObject1.getString("paySign"));
                        }
                        prepayId = jsonObject1.getString("prepay_id");

                        if (CommonUtil.isNull(jsonObject1.getString("prepay_id"))) {
                            prepayId = jsonObject1.getString("package");
                        }
                    }

                    if (!CommonUtil.isNull(jsonObject.getString("paySignType"))) {
                        map.put("signType", jsonObject.getString("paySignType"));
                    }

                    if (!CommonUtil.isNull(jsonObject.getString("payAppId"))) {
                        map.put("appid", jsonObject.getString("payAppId"));
                    }

                    if (!CommonUtil.isNull(jsonObject.getString("paynonceStr"))) {
                        map.put("nonceStr", jsonObject.getString("paynonceStr"));
                    }

                    if (!CommonUtil.isNull(jsonObject.getString("paySign"))) {
                        map.put("sign", jsonObject.getString("paySign"));
                    }

                    if (!CommonUtil.isNull(jsonObject.getString("payPackage"))) {
                        prepayId = jsonObject.getString("payPackage");
                    }
                    if (prepayId != null && prepayId.startsWith("prepay_id=")) {
                        prepayId = prepayId.substring(10);
                    }
                    map.put("prepayId", prepayId);

                    if (!CommonUtil.isNull(jsonObject.getString("ordNo"))) {
                        map.put("outTradeNo", jsonObject.getString("ordNo"));
                    }

                    if (!CommonUtil.isNull(jsonObject.getString("payTimeStamp"))) {
                        map.put("timeStamp", jsonObject.getString("payTimeStamp"));
                    }

                    map.put("type", 1);

                    log.info("随行付返回【{}】  ", map);

                }

            }
            if (null == map.get("type")) {
                return ResultUtil.error(ResultEnum.Err_2030);
            }

            return ResultUtil.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{} 5sxhq6z5 】,机器号:【{}】,请求参数:【{}】,异常1:【{}】,行号:【{}】", "支付请求（主扫）", machno, request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    private void getWallet(EntityXfRecordProcess entityXfRecordProcess, EntityConsTypeConfig entityConsTypeConfig, EntityXfAccountInfo entityXfAccountInfo, EntityXfSubAccountList entityXfSubAccountList) {
        //非金额0  非计次
        if (entityXfRecordProcess.getRealMoney() != 0l && entityXfRecordProcess.getOpTypeDiff() != 0l) {
            if (entityConsTypeConfig.getSubAccount() == 0) {
                //字符串：空表示不允许使用虚拟账户扣款,扣款顺序（1现金钱包、2补贴钱包）
                String walletSerial = "21";
                if (entityConsTypeConfig != null) {
                    if (entityConsTypeConfig.getWalletSerial() != null) {
                        walletSerial = entityConsTypeConfig.getWalletSerial();
                    }
                }
                if (walletSerial.equals("2")) {
                    //补贴钱包
                    Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney();
                    entityXfRecordProcess.setSubBalance(subBalance);
                    entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                    entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setChargeMoney(0L);
                } else if (walletSerial.equals("21")) {
                    //先扣补贴钱包，再扣现金钱包
                    Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney();
                    if (subBalance < 0) {
                        Long chargeBalance = subBalance + entityXfAccountInfo.getAccountRechargeMoney();
                        entityXfRecordProcess.setSubBalance(0L);
                        entityXfRecordProcess.setSubMoney(-entityXfAccountInfo.getAccountSubsidyMoney());

                        entityXfRecordProcess.setChargeBalance(chargeBalance);
                        entityXfRecordProcess.setChargeMoney(subBalance);
                    } else {
                        entityXfRecordProcess.setSubBalance(subBalance);
                        entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                        entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                        entityXfRecordProcess.setChargeMoney(0L);
                    }
                } else if (walletSerial.equals("12")) {
                    //先扣现金钱包，再扣补贴钱包
                    Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney();
                    if (chargeBalance < 0) {
                        Long subBalance = chargeBalance + entityXfAccountInfo.getAccountSubsidyMoney();
                        entityXfRecordProcess.setSubBalance(subBalance);
                        entityXfRecordProcess.setSubMoney(chargeBalance);
                        entityXfRecordProcess.setChargeBalance(0L);
                        entityXfRecordProcess.setChargeMoney(-entityXfAccountInfo.getAccountRechargeMoney());
                    } else {
                        entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                        entityXfRecordProcess.setChargeBalance(chargeBalance);
                        entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                        entityXfRecordProcess.setSubMoney(0L);
                    }
                } else {
                    //现金钱包
                    Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney();
                    entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                    entityXfRecordProcess.setChargeBalance(chargeBalance);
                    entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setSubMoney(0L);
                }

                entityXfRecordProcess.setOpTypeDiff(100l);
            } else {
                if (CommonUtil.isNull(entityXfRecordProcess.getReserved3())) {
                    entityXfRecordProcess.setReserved3("");  //准备记录钱包编号
                }
                entityXfRecordProcess.setReserved3(entityXfRecordProcess.getReserved3() + "#使用钱包编号:" + entityConsTypeConfig.getSubAccount());
                //字符串：空表示不允许使用虚拟账户扣款,扣款顺序（1现金钱包、2补贴钱包）
                String walletSerial = "21";
                if (entityConsTypeConfig != null) {
                    if (entityConsTypeConfig.getWalletSerial() != null) {
                        walletSerial = entityConsTypeConfig.getWalletSerial();
                    }
                }
                if (walletSerial.equals("2")) {
                    //补贴钱包
                    Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountSubsidyMoney();
                    entityXfRecordProcess.setSubBalance(subBalance);
                    entityXfRecordProcess.setChargeBalance(entityXfSubAccountList.getAccountRechargeMoney().longValue());
                    entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setChargeMoney(0L);
                } else if (walletSerial.equals("21")) {
                    //先扣补贴钱包，再扣现金钱包
                    Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountSubsidyMoney();
                    if (subBalance < 0) {
                        Long chargeBalance = subBalance + entityXfSubAccountList.getAccountRechargeMoney();
                        entityXfRecordProcess.setSubBalance(0L);
                        entityXfRecordProcess.setSubMoney(-entityXfSubAccountList.getAccountSubsidyMoney().longValue());

                        entityXfRecordProcess.setChargeBalance(chargeBalance);
                        entityXfRecordProcess.setChargeMoney(subBalance);
                    } else {
                        entityXfRecordProcess.setSubBalance(subBalance);
                        entityXfRecordProcess.setChargeBalance(entityXfSubAccountList.getAccountRechargeMoney().longValue());
                        entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                        entityXfRecordProcess.setChargeMoney(0L);
                    }
                } else if (walletSerial.equals("12")) {
                    //先扣现金钱包，再扣补贴钱包
                    Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountRechargeMoney();
                    if (chargeBalance < 0) {
                        Long subBalance = chargeBalance + entityXfSubAccountList.getAccountSubsidyMoney();
                        entityXfRecordProcess.setSubBalance(subBalance);
                        entityXfRecordProcess.setSubMoney(chargeBalance);
                        entityXfRecordProcess.setChargeBalance(0L);
                        entityXfRecordProcess.setChargeMoney(-entityXfSubAccountList.getAccountRechargeMoney().longValue());
                    } else {
                        entityXfRecordProcess.setSubBalance(entityXfSubAccountList.getAccountSubsidyMoney().longValue());
                        entityXfRecordProcess.setChargeBalance(chargeBalance);
                        entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                        entityXfRecordProcess.setSubMoney(0L);
                    }
                } else {
                    //现金钱包
                    Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfSubAccountList.getAccountRechargeMoney();
                    entityXfRecordProcess.setSubBalance(entityXfSubAccountList.getAccountSubsidyMoney().longValue());
                    entityXfRecordProcess.setChargeBalance(chargeBalance);
                    entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setSubMoney(0L);
                }
            }
        }else{
            entityXfRecordProcess.setChargeMoney(0l);
            entityXfRecordProcess.setSubMoney(0l);
        }
    }


    //现金消费
    @PostMapping(PayHandleUrl.cashPay)
    public Result cashPayDiches(@RequestBody CashPayRequest request) {
        try {

            String tradeNoRedis = "cashPay:" + request.getCompanyId() + ":" + request.getMachNo() + ":" + request.getTradeNo();
            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
                log.info("请求方式:【{} 5aal31l5 】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            //判断是什么支付类型
            //1-刷卡，4-刷脸，5-付款码，7-ocom离线码 8微信人脸
            EntityXfAccountInfo entityXfAccountInfo = null;
            EntityPersonnelInfo entityPersonnelInfo = null;
            EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
            EntityCardInfo entityCardInfo = null;
            if (request.getType() == 1) {
                //刷卡
                entityCardInfo = xfCardInfoService.selectCard(request.getCompanyId(), request.getAuthCode());
                if (entityCardInfo == null) {
                    return ResultUtil.error(ResultEnum.Err_305);
                }
                if (entityCardInfo.getCardState() != 1) {
                    return ResultUtil.error(ResultEnum.Err_4021);
                }
                String strNewDate = DateUtils.getStrDate(new Date(), "yyyy-MM-dd");
                String strEndDate = DateUtils.getStrDate(entityCardInfo.getEndDate(), "yyyy-MM-dd");
                if (!DateUtils.compare(strNewDate, strEndDate)) {
                    return ResultUtil.error(ResultEnum.Err_4025);
                }
                //用账号查询账号表和人员的信息
                entityXfAccountInfo = xfAccountInfoService.selectAccount(request.getCompanyId(), entityCardInfo.getAccountNo());
                entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), entityCardInfo.getPId());

                //操作类型：
                //20：线上充值
                entityXfRecordProcess.setOpType(11l);
                entityXfRecordProcess.setAccountNo(entityCardInfo.getAccountNo());
            } else {
                Long pId = 0l;
                try {
                    if (!CommonUtil.isNull(request.getAuthCode())) {
                        pId = Long.valueOf(request.getAuthCode());
                        if (pId != null && pId > 0l) {
                            entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), pId);
                            entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), pId);
                            entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
                        }
                    }
                } catch (Exception exception) {
                    log.info("请求方式:【{}】,代码:【{}】 ,机器号:【{}】,请求参数:【{}】,异常:【{}】", "支付请求（强在线）", "获取人员信息", request.getMachNo(), request, exception);
                }

                entityXfRecordProcess.setOpType(11l);
            }
            entityXfRecordProcess.setSubBalance(0l);
            entityXfRecordProcess.setChargeBalance(0l);
            entityXfRecordProcess.setComId(request.getCompanyId());
            entityXfRecordProcess.setDeviceNo(request.getMachNo());
            entityXfRecordProcess.setCardNo(request.getAuthCode());
            if (entityXfAccountInfo != null) {
                entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
                entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountRechargeMoney());
                entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                entityXfRecordProcess.setAccTypeId(entityXfAccountInfo.getAccTypeId());
            }
            if (entityPersonnelInfo != null) {
                entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
                entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
            }
            Date date = new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
            //查询收费的和商家信息
            payHandleFunService.relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getMachNo(), date);
            if (request.getConsState() == 5) {
                payHandleFunService.relatedDingCan(entityXfRecordProcess, request.getConsDate(), request.getConsMeal(), request.getConsPoint());
            }
            //查询个人所在的组织
            if (entityPersonnelInfo != null) {
                entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
                if (entityPersonnelInfo.getDeptId() == null) {
                    entityPersonnelInfo.setDeptId(0l);
                }
                EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getCompanyId(), entityPersonnelInfo.getDeptId());
                if (entityDeptInfo != null) {
                    entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
                }
            }


            entityXfRecordProcess.setMealDate(DateUtils.getDate(DateUtils.getStrDate(date, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD));
            //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
            entityXfRecordProcess.setConsState(request.getConsState());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());

            //判断扣款
            int consMoney = -request.getAmount();
            //计算金额
            entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));
            //计算优惠
            entityXfRecordProcess.setConsType(request.getConsType());
            entityXfRecordProcess.setOpTypeDiff(1l);


            //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
            entityXfRecordProcess.setPayState(1);
            entityXfRecordProcess.setDiscount(0l);
            entityXfRecordProcess.setRealMoney(-1 * Long.valueOf(Math.abs(request.getAmount())));
            entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(request.getAmount())));
            entityXfRecordProcess.setPayTime(new Date());
            entityXfRecordProcess.setConsTime(entityXfRecordProcess.getPayTime());

            if (request.getConsState() == 3) {
                payHandleFunService.relatedReceiptNo(entityXfRecordProcess);
            }

            if (request.getConsDate() != null)
                entityXfRecordProcess.setMealDate(DateUtils.strToDate2(request.getConsDate()));
            if (request.getConsMeal() != null) entityXfRecordProcess.setMealNo(String.valueOf(request.getConsMeal()));


            //插入订单
            try {
                int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_3030);
                }
                try {
                    if (request.getConsState() == 3 || request.getConsState() == 5) {
                        xfGoodsListProcessService.saveXfGoodsList(request.getCompanyId(), entityXfRecordProcess, request.getMealData());
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式:【{}】,机器号:【{}】,现金支付-入库新增菜品缓存表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                }

                MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                mqSaveOrderVo.setComId(request.getCompanyId());
                mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

                //支付成功
                Map<String, Object> map = new HashMap<>();

                map.put("discount", entityXfRecordProcess.getDiscount());
                map.put("payAmount", Math.abs(entityXfRecordProcess.getRealMoney()));
                Map<String, Object> mapAccountInf = new HashMap<>();
                mapAccountInf.put("name", entityXfRecordProcess.getPName());

                mapAccountInf.put("money", entityXfRecordProcess.getChargeBalance());
                mapAccountInf.put("allowance", entityXfRecordProcess.getSubBalance());
                if (entityCardInfo != null) {
                    mapAccountInf.put("expireDate", DateUtils.getStrDate(entityCardInfo.getEndDate(), DateUtils.YYYY_MM_DD_HH_MM_SS));
                }
                if (entityXfAccountInfo == null) {
                    mapAccountInf.put("cardtype", 0);
                } else {
                    mapAccountInf.put("cardtype", entityXfAccountInfo.getAccTypeId());
                }
                map.put("accountInf", mapAccountInf);
                map.put("pickupNum", entityXfRecordProcess.getReceiptNo());
                map.put("orderTime", DateUtil.getDateTime(entityXfRecordProcess.getPayTime()));
                return ResultUtil.success(map);
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{}】,机器号:【{}】,入库新增等待表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_3030);
            }

        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,异常2:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }


    //查询餐段订餐信息

    @PostMapping(PayHandleUrl.URL_getOrderListByMeal)
    public Result getOrderListByMeal(@RequestBody GetOrderListByMealRequest request) {
        List<OrderMealListVo> list = xfGoodsListProcessService.getOrderListByMeal(request.getCompanyId(), request.getPId(), request.getMealDate(), request.getMealNo());

        if (list == null || list.size() <= 0) {
            return ResultUtil.success(new ArrayList<>());
        }

        List<MealOrderListVo> mealOrderListVos = new ArrayList<>();
        for (OrderMealListVo orderMealListVo : list) {
            MealOrderListVo mealOrderListVo = new MealOrderListVo();

            mealOrderListVo.setMenuName(orderMealListVo.getMenuName());
            mealOrderListVo.setMenuCode(orderMealListVo.getMenuCode());
            mealOrderListVo.setMealNo(orderMealListVo.getMealNo());
            mealOrderListVo.setPhotoUrl(orderMealListVo.getPhotoUrl());
            if (orderMealListVo.getReceiptId() == -1) {
                mealOrderListVo.setAddress(orderMealListVo.getReceiptName());
            }
            if (orderMealListVo.getReceiptId() == 0) {
                mealOrderListVo.setAddress(orderMealListVo.getPointName());
            }
            mealOrderListVos.add(mealOrderListVo);

            //(1)


            //(2)


        }

        return ResultUtil.success(mealOrderListVos);
    }


    //小程序点餐
    @PostMapping(PayHandleUrl.URL_PayHandle_orderDishesPay2)
    public Result orderDishesPay2(@RequestBody OrderDishesPayRequest request) {

        String machno = "";
        String tradeNo = "";
        try {
            machno = request.getMachNo();
            if (StringUtils.isNumeric(request.getMachNo())) {
                machno = request.getMachNo();
            } else {
                machno = "00000000";
            }
            Long companyID = request.getComId();
            //向redis分布式锁插入订单号是否重复
            //向redis分布式锁插入订单号是否重复
            tradeNo = request.getTradeNo();
            String tradeNoRedis = "orderDishesPay:" + companyID + ":" + machno + ":" + tradeNo;
            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（主扫）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
            entityXfRecordProcess.setDeviceName("点餐订餐");

            if (request.getType() == 7) {
                entityXfRecordProcess.setOpType(21l);
                entityXfRecordProcess.setOpTypeDiff(100l);
            } else {
                entityXfRecordProcess.setOpType(12l);//小程序点餐
                entityXfRecordProcess.setOpTypeDiff(201l);
            }
            entityXfRecordProcess.setConsType(request.getConsType());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPlatOrderNo(request.getTradeNo());
            entityXfRecordProcess.setCardNo(request.getOpenId());
            entityXfRecordProcess.setReceiptName(request.getReceiptName());
            entityXfRecordProcess.setReceiptId(request.getReceiptId());

            if (request.getConsState() == 3 || request.getConsState() == 5) {
                payHandleFunService.relatedReceiptNo(entityXfRecordProcess);
            }

            //判断消费时间段
            Date date = new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
            //查询收费的和商家信息
            //		relatedDevice(entityXfRecordProcess, request.getComId(), request.getMachNo(), date);

            entityXfRecordProcess.setComId(companyID);
            entityXfRecordProcess.setPointId(request.getPointId().longValue());
            entityXfRecordProcess.setMerchId(0l);
            entityXfRecordProcess.setMerchName("本单位");
            //有消费点
            if (request.getPointId() > 0l) {
                EntityXfPointInfo entityXfPointInfo = xfPointInfoService.getTollPointInfo(companyID, request.getPointId());
                if (entityXfPointInfo != null) {
                    entityXfRecordProcess.setPointName(entityXfPointInfo.getPointName());

                    if (entityXfPointInfo.getMerchId() != 0) {
                        EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.getMerchInfo(entityXfPointInfo.getComId(), entityXfPointInfo.getMerchId());
                        entityXfRecordProcess.setMerchId(entityXfPointInfo.getMerchId().longValue());
                        entityXfRecordProcess.setMerchName(entityXfMerchantInfo.getMerchName());
                    }
                }
            } else {
                entityXfRecordProcess.setPointName("本单位");
            }
            entityXfRecordProcess.setComId(request.getComId());
            entityXfRecordProcess.setDeviceNo(machno);

            //计算金额
            int consMoney = -request.getAmount();
            entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));

            Integer intMealNo = 0;
            if (request.getMealNo() != null) {
                intMealNo = request.getMealNo();
            }
//            int discount =  xfDiscountConfigServcie.selectSiscount(request.getComId(),entityXfAccountInfo.getPId(),
//                    entityXfAccountInfo.getAccTypeId(),request.getConsType(),date,intMealNo,request.getAmount(),entityXfRecordProcess);
            int discount = 0;
            int realMoney = consMoney + discount;
            //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setDiscount(Long.valueOf(discount));
            entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
            entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));
            //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
            entityXfRecordProcess.setConsState(request.getConsState());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPayWay(request.getPayWay());
            entityXfRecordProcess.setMealNo(String.valueOf(request.getMealNo()));
            entityXfRecordProcess.setMealDate(DateUtils.strToDate2(request.getMealDate()));
            entityXfRecordProcess.setConsTime(new Date());
            entityXfRecordProcess.setReserved3(request.getRemark());

            if (null != request.getPId() && 0 < request.getPId()) {
                EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getComId(), request.getPId());
                EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getComId(), request.getPId());
                entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
                entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
                entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
                entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
                //查询个人所在的组织
                entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
                if (entityPersonnelInfo.getDeptId() == null || entityPersonnelInfo.getDeptId() == 0l) {
                    entityPersonnelInfo.setDeptId(0l);
                } else {
                    EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getComId(), entityPersonnelInfo.getDeptId());
                    if (entityDeptInfo != null) {
                        entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
                    }
                }

                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                entityXfRecordProcess.setSubMoney(0L);
            }

            try {
                int i = xfRecordProcessService.insertEntityXfRecord(companyID, entityXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{}】,机器号:【{}】,入库新增等待表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            //保存菜品 2023年5月23日13:52:16
            try {
                if (request.getDishesInfo() != null && request.getDishesInfo().size() > 0) {
                    List<EntityXfGoodsListProcess> entityXfGoodsListProcesses = new ArrayList<>();
                    if (entityXfRecordProcess.getMerchId() == null) entityXfRecordProcess.setMerchId(0l);
                    if (entityXfRecordProcess.getDeptId() == null) entityXfRecordProcess.setDeptId(0l);
                    if (entityXfRecordProcess.getPId() == null) entityXfRecordProcess.setPId(0l);
                    for (DishesInfoVo dishesInfoVo : request.getDishesInfo()) {
                        EntityXfGoodsListProcess entityXfGoodsListProcess = new EntityXfGoodsListProcess();
                        entityXfGoodsListProcess.setComId(request.getComId());
                        entityXfGoodsListProcess.setDeviceNo(entityXfRecordProcess.getDeviceNo());
                        entityXfGoodsListProcess.setPointId(entityXfRecordProcess.getPointId().intValue());
                        entityXfGoodsListProcess.setMerchId(entityXfRecordProcess.getMerchId().intValue());
                        entityXfGoodsListProcess.setPId(entityXfRecordProcess.getPId().longValue());
                        entityXfGoodsListProcess.setDeptId(entityXfRecordProcess.getDeptId().intValue());
                        entityXfGoodsListProcess.setReceiptId(request.getReceiptId());
                        entityXfGoodsListProcess.setReceiptName(request.getReceiptName());
                        entityXfGoodsListProcess.setOrderNo(entityXfRecordProcess.getOrderNo());

                        entityXfGoodsListProcess.setConsTime(entityXfRecordProcess.getConsTime());
                        entityXfGoodsListProcess.setMealDate(entityXfRecordProcess.getMealDate());
                        entityXfGoodsListProcess.setMealNo(request.getMealNo());
                        entityXfGoodsListProcess.setConsType(request.getConsType());
                        entityXfGoodsListProcess.setIfRefund(0);
                        entityXfGoodsListProcess.setDishesId(dishesInfoVo.getDishesId());
                        entityXfGoodsListProcess.setDishesName(dishesInfoVo.getDishesName());
                        entityXfGoodsListProcess.setPriceMode(dishesInfoVo.getPriceMode());
                        entityXfGoodsListProcess.setWeightNumber(dishesInfoVo.getWeightNumber());
                        entityXfGoodsListProcess.setDishesPrice(dishesInfoVo.getDishesPrice());
                        entityXfGoodsListProcess.setUnitPrice(dishesInfoVo.getUnitPrice());
                        entityXfGoodsListProcess.setMonthValue(entityXfRecordProcess.getMonthValue());
                        entityXfGoodsListProcess.setCreateTime(new Date());

                        entityXfGoodsListProcesses.add(entityXfGoodsListProcess);
                    }
                    xfGoodsListProcessService.addXfGoodsListProcessList(request.getComId(), entityXfGoodsListProcesses);
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{}】,机器号:【{}】,入库菜品缓存表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_900));
            }

            //查询配置信息向统一平台发起支付
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = payHandleFunService.configure(entityXfRecordProcess);
//				EntiyXfMerchPayInfo entiyXfMerchPayInfo=xfMerchPayInfoService.selectConfigure(request.getCompanyId(),0L);


            if (entiyXfMerchPayInfo == null) {
                //商户支付渠道未配置"
                return ResultUtil.error(ResultEnum.Err_3048);
            }

            EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
            updateXfRecordProcess.setId(entityXfRecordProcess.getId());
            updateXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
            try {
                int i = xfRecordProcessService.updateEntityXfRecord(companyID, updateXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "支付请求（主扫）", machno, updateXfRecordProcess, "等待表修改入库失败");
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（主扫）", machno, updateXfRecordProcess, e, ste.getLineNumber());
            }
            String payUrl = companyInfoService.getPayCenterUrl(companyID,entiyXfMerchPayInfo.getCompanyId());
            String RealUrl = payUrl + "/unifiedpreorder/lordesau.do";

            Map<String, Object> stringObjectMap = new HashMap<>();
            stringObjectMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
            stringObjectMap.put("password", entiyXfMerchPayInfo.getPassword());
            stringObjectMap.put("user_name", entiyXfMerchPayInfo.getUserName());

            Gson gson = new Gson();
            Map<String, Object> map = new HashMap<>();

            map.put("totalFee", request.getAmount());

            if (request.getType() == 1) {
                //建行公众号      //1 和  5小程序反了   这里1  建行公众号

                stringObjectMap.put("pos_no", "00000000");
                stringObjectMap.put("devsnip", "127.0.0.1");
                stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                stringObjectMap.put("subject", "小程序点餐");
                stringObjectMap.put("total_amount", request.getAmount());
                stringObjectMap.put("fee_type", "CNY");
                stringObjectMap.put("trade_type", "JSAPI");

                stringObjectMap.put("payway", 7);
                stringObjectMap.put("body", request.getComId().toString());
                stringObjectMap.put("operator", "admin");
                stringObjectMap.put("openid", request.getOpenId());
//		stringObjectMap.put("notify_url","");

                RequestUtil requestUtil = new RequestUtil();

                log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

                Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

                Result result3 = gson.fromJson(gson.toJson(re), Result.class);

                log.info("返回【{}】  ", result3);

                if (result3 == null || result3.getCode() != 200) {
                    return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
                    /**
                     Map<String,Object> map =new HashMap<>();
                     map.put("outTradeNo","nrFqKJYvQooEtXdTXVKKHVPkkgXxj3Lq");
                     map.put("timeStamp","1657084272");
                     map.put("nonceStr","B7RhLtRQ5XkpLk0h");
                     map.put("appid","wx7b35e13388684b68");
                     map.put("sign","E315466DA8AFD4709DED09A3BB6A0568");
                     map.put("mchId","1483737272");
                     map.put("prepayId","wx06131112573065de8b46e350ebafdc0000");
                     return ResultUtil.success(map);
                     **/
                }

                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
                JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));

                //jsonObject1 判断
//			if(result3 == null || result3.getCode()!=200) {
//				return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
//			}

                map.put("outTradeNo", jsonObject.getString("out_trade_no"));
                map.put("timeStamp", jsonObject1.getString("timeStamp"));
                map.put("nonceStr", jsonObject1.getString("nonceStr"));
                map.put("appid", jsonObject1.getString("appId"));
                map.put("sign", jsonObject1.getString("paySign"));
                map.put("signType", jsonObject1.getString("signType"));
                String prepayId = jsonObject1.getString("package");
                if (prepayId != null && prepayId.startsWith("prepay_id=")) {
                    prepayId = prepayId.substring(10);
                }
                map.put("prepayId", prepayId);
                map.put("type", 1);

                log.info("龙支付返回【{}】  ", map);

            } else if (request.getType() == 2 || request.getType() == 3) {
                //随行付
                stringObjectMap.put("pos_no", "00000000");
                stringObjectMap.put("devsnip", "127.0.0.1");
                stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                stringObjectMap.put("subject", "小程序点餐");
                stringObjectMap.put("total_amount", request.getAmount());
                stringObjectMap.put("fee_type", "CNY");
                stringObjectMap.put("trade_type", "JSAPI");
                stringObjectMap.put("payway", 3);
                stringObjectMap.put("body", request.getComId().toString());
                stringObjectMap.put("operator", "admin");
                stringObjectMap.put("openid", request.getOpenId());
//		stringObjectMap.put("notify_url","");

                RequestUtil requestUtil = new RequestUtil();

                log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

                Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

                Result result3 = gson.fromJson(gson.toJson(re), Result.class);

                log.info("返回【{}】  ", result3);

                if (result3 == null || result3.getCode() != 200) {
                    return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
                }
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
                JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));

                map.put("outTradeNo", jsonObject.getString("out_trade_no"));
                String prepayId = "";

                map.put("appid", jsonObject.getString("payAppId"));
                if (jsonObject1 != null) {
                    map.put("timeStamp", jsonObject1.getString("timeStamp"));
                    map.put("nonceStr", jsonObject1.getString("nonce_str"));
                    map.put("appid", jsonObject1.getString("appid"));
                    map.put("sign", jsonObject1.getString("sign"));
                    map.put("mchId", jsonObject1.getString("mch_id"));
                    map.put("signType", jsonObject1.getString("signType"));
                    map.put("mchId", jsonObject1.getString("mch_id"));


                    if (CommonUtil.isNull(jsonObject1.getString("signType"))) {
                        map.put("signType", "MD5");
                    }
                    if (!CommonUtil.isNull(jsonObject1.getString("appid"))) {
                        map.put("appid", jsonObject1.getString("appId"));
                    }
                    if (!CommonUtil.isNull(jsonObject1.getString("nonce_str"))) {
                        map.put("nonceStr", jsonObject1.getString("nonceStr"));
                    }
                    if (!CommonUtil.isNull(jsonObject1.getString("sign"))) {
                        map.put("sign", jsonObject1.getString("paySign"));
                    }
                    prepayId = jsonObject1.getString("prepay_id");

                    if (CommonUtil.isNull(jsonObject1.getString("prepay_id"))) {
                        prepayId = jsonObject1.getString("package");
                    }
                }

                if (!CommonUtil.isNull(jsonObject.getString("paySignType"))) {
                    map.put("signType", jsonObject.getString("paySignType"));
                }

                if (!CommonUtil.isNull(jsonObject.getString("payAppId"))) {
                    map.put("appid", jsonObject.getString("payAppId"));
                }

                if (!CommonUtil.isNull(jsonObject.getString("paynonceStr"))) {
                    map.put("nonceStr", jsonObject.getString("paynonceStr"));
                }

                if (!CommonUtil.isNull(jsonObject.getString("paySign"))) {
                    map.put("sign", jsonObject.getString("paySign"));
                }

                if (!CommonUtil.isNull(jsonObject.getString("payPackage"))) {
                    prepayId = jsonObject.getString("payPackage");
                }
                if (prepayId != null && prepayId.startsWith("prepay_id=")) {
                    prepayId = prepayId.substring(10);
                }
                map.put("prepayId", prepayId);

                if (!CommonUtil.isNull(jsonObject.getString("ordNo"))) {
                    map.put("outTradeNo", jsonObject.getString("ordNo"));
                }

                if (!CommonUtil.isNull(jsonObject.getString("payTimeStamp"))) {
                    map.put("timeStamp", jsonObject.getString("payTimeStamp"));
                }

                map.put("type", 1);

                log.info("随行付返回【{}】  ", map);

            } else if (request.getType() == 7) {
            //余额支付
                try {
                    Boolean bo = xfRecordProcessService.saveLxOrder2(entityXfRecordProcess.getComId(), entityXfRecordProcess, 0, null);
                    if (!bo) {
                        return ResultUtil.error(ResultEnum.Err_4069);
                    }

                    Boolean aBoolean = xfGoodsListProcessService.saveXfGoodsListRecode(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrderNo());

                    //新增成功表的退款数据
                    Date payTime = new Date();
                    entityXfRecordProcess.setPayTime(payTime);
                    entityXfRecordProcess.setPayState(1);


                    MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                    mqSaveOrderVo.setComId(entityXfRecordProcess.getComId());
                    mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                    mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                    saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

//                    Result sveResult = xfRecordFeign.sveXfRecord(entityXfRecordProcess);

                    log.info("迁移订餐结果到成功表 【{}】【{}】", entityXfRecordProcess.getOrderNo(), aBoolean);

//                    if (200 == sveResult.getCode()) {
//                        try {
//                            if (3 == entityXfRecordProcess.getConsState()) {
//                                log.info("开始打印订单 订单：【{}】",entityXfRecordProcess);
//                                PlanKitchenPrinterRequest planKitchenPrinterRequest = new PlanKitchenPrinterRequest();
//                                planKitchenPrinterRequest.setComId(entityXfRecordProcess.getComId());
//                                planKitchenPrinterRequest.setPointId(entityXfRecordProcess.getPointId());
//                                planKitchenPrinterRequest.setOrderNo(entityXfRecordProcess.getOrderNo());
//                                planKitchenPrinterRequest.setCheckPrint(true);
//
//                                log.info("开始打印订单 planKitchenPrinter：【{}】",planKitchenPrinterRequest);
//                                Result printResult = payConfigClientService.planKitchenPrinter(planKitchenPrinterRequest);
//                                log.info("订单打印结果【{}】",printResult);
//                            }
//                        }catch (Exception e) {
//                            e.printStackTrace();
//                            log.info("订单打印异常 【{}】【{}】",entityXfRecordProcess, e);
//                        }
//                    }

                    map.put("type", 7);
                    map.put("result", "success");
                    map.put("orderNo", entityXfRecordProcess.getOrderNo());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("订餐异常 【{}】", request);
                    return ResultUtil.error(ResultEnum.Err_3030);
                }

            } else if(request.getType() == 5) {
                //1 和  5小程序反了   这里5微信官方
                stringObjectMap.put("pos_no", "00000000");
                stringObjectMap.put("devsnip", "127.0.0.1");
                stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                stringObjectMap.put("subject", "小程序点餐");
                stringObjectMap.put("total_amount", request.getAmount());
                stringObjectMap.put("fee_type", "CNY");
                stringObjectMap.put("trade_type", "JSAPI");
                stringObjectMap.put("payway", 3);
                stringObjectMap.put("body", request.getComId().toString());
                stringObjectMap.put("operator", "admin");
                stringObjectMap.put("openid", request.getOpenId());
//		stringObjectMap.put("notify_url","");

                RequestUtil requestUtil=new RequestUtil();

                log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);

                Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));

                Result result3 = gson.fromJson(gson.toJson(re),Result.class);

                log.info("返回【{}】  ",result3);

                if(result3 == null || result3.getCode()!=200){
                    return ResultUtil.info(result3.getCode(),result3.getMsg(),result3.getData());
                    /**
                     Map<String,Object> map =new HashMap<>();
                     map.put("outTradeNo","nrFqKJYvQooEtXdTXVKKHVPkkgXxj3Lq");
                     map.put("timeStamp","1657084272");
                     map.put("nonceStr","B7RhLtRQ5XkpLk0h");
                     map.put("appid","wx7b35e13388684b68");
                     map.put("sign","E315466DA8AFD4709DED09A3BB6A0568");
                     map.put("mchId","1483737272");
                     map.put("prepayId","wx06131112573065de8b46e350ebafdc0000");
                     return ResultUtil.success(map);
                     **/
                }

                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
                JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));

                map.put("outTradeNo",jsonObject.getString("out_trade_no"));
                map.put("timeStamp",jsonObject1.getString("timeStamp"));
                map.put("nonceStr",jsonObject1.getString("nonce_str"));
                map.put("appid",jsonObject1.getString("appid"));
                map.put("sign",jsonObject1.getString("sign"));
                map.put("mchId",jsonObject1.getString("mch_id"));
                map.put("signType",jsonObject1.getString("signType"));

                if(CommonUtil.isNull(jsonObject1.getString("signType"))){
                    map.put("signType","MD5");
                }

                if(CommonUtil.isNull(jsonObject1.getString("appid"))){
                    map.put("appid",jsonObject1.getString("appId"));
                }
                if(CommonUtil.isNull(jsonObject1.getString("nonce_str"))){
                    map.put("nonceStr",jsonObject1.getString("nonceStr"));
                }
                if(CommonUtil.isNull(jsonObject1.getString("sign"))){
                    map.put("sign",jsonObject1.getString("paySign"));
                }

                String prepayId  = jsonObject1.getString("prepay_id");
                if(CommonUtil.isNull(jsonObject1.getString("prepay_id"))){
                    prepayId  = jsonObject1.getString("package");
                }

                map.put("mchId",jsonObject1.getString("mch_id"));

                if(prepayId!=null && prepayId.startsWith("prepay_id=")){
                    prepayId=prepayId.substring(10);
                }
                map.put("prepayId",prepayId);
                map.put("type",1);

            } else {
                return ResultUtil.error(ResultEnum.Err_2030, map);
            }

            return ResultUtil.success(map);

        } catch (Exception e) {
            e.printStackTrace();
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,异常1:【{}】,行号:【{}】", "支付请求（主扫）", machno, request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }


    //核销
    @PostMapping(PayHandleUrl.URL_orderVerification)
    public Result orderVerification(@RequestBody OrderVerificationRequest request) {

        String dateOrder = DateUtils.getStrDate(new Date(), "yyyy-MM-dd");


        DeviceInfoVo deviceInfoVo = payHandleFunService.selectDeviceInfo(request.getCompanyId(), request.getMachNo());

        Integer mealNo = payHandleFunService.selectMealNo(request.getCompanyId(), deviceInfoVo.getPointId(),0, new Date());

        if (deviceInfoVo == null) {
            return ResultUtil.error(ResultEnum.Err_2013);
        }


        EntityXfRecordProcess entityXfRecordProcess = null;
        Long pId = 0l;

        if (request.getType() == 4 || request.getType() == 7) {
            pId = Integer.valueOf(request.getAuthCode()).longValue();
        }
        EntityCardInfo entityCardInfo = null;
        if (request.getType() == 1) {
            //刷卡
            entityCardInfo = xfCardInfoService.selectCard(request.getCompanyId(), request.getAuthCode());
            if (entityCardInfo == null) {
                return ResultUtil.error(ResultEnum.Err_305);
            }
            if (entityCardInfo.getCardState() != 1) {
                return ResultUtil.error(ResultEnum.Err_4021);
            }
            pId = entityCardInfo.getPId();
        }

        if(request.getType() == 26){
            entityXfRecordProcess = xfRecordProcessService.getReadyOrderVer(request.getCompanyId(),deviceInfoVo.getPointId(), pId,dateOrder,mealNo,request.getAuthCode());
            if(entityXfRecordProcess == null ){
                return ResultUtil.error(ResultEnum.Err_805);
            }
            if (entityXfRecordProcess.getVerification() == 1) {
                return ResultUtil.error(ResultEnum.Err_2041);
            }
            pId = entityXfRecordProcess.getPId();
        }else{
            if(pId == 0l){
                return ResultUtil.error(ResultEnum.Err_4017);
            }
            entityXfRecordProcess = xfRecordProcessService.getReadyOrderVer(request.getCompanyId(),deviceInfoVo.getPointId(), pId,dateOrder,mealNo,null);
            if(entityXfRecordProcess == null ){
                return ResultUtil.error(ResultEnum.Err_805);
            }
        }
        //原月份 保留可以修改
        String  monthVv = entityXfRecordProcess.getMonthValue();
        String  orderNoV = entityXfRecordProcess.getOrderNo();

        EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), pId);
        if (entityXfAccountInfo == null) {
            return ResultUtil.error(ResultEnum.Err_3049);
        }
        EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), pId);
        if (entityPersonnelInfo == null) {
            return ResultUtil.error(ResultEnum.Err_4017);
        }
        if (entityPersonnelInfo.getStatus() != 0) {
            return ResultUtil.error(ResultEnum.Err_4023);
        }

        List<EntityXfGoodsListProcess> entityXfGoodsListProcess1 = xfGoodsListProcessService.getXfGoodsList(request.getCompanyId(),orderNoV);

//        //获取点餐信息
//        List<EntityXfGoodsListProcess> entityXfGoodsListProcess1 = xfGoodsListProcessService.getUserMeal(request.getCompanyId(),
//                deviceInfoVo.getPointId().intValue(),
//                pId,
//                dateOrder,
//                mealNo
//        );
//
//        if (entityXfGoodsListProcess1 == null || entityXfGoodsListProcess1.size() == 0) {
//            return ResultUtil.error(ResultEnum.Err_3097);
//        }
//
//        EntityXfGoodsListProcess entityXfGoodsListProcess = entityXfGoodsListProcess1.get(0);
//
//        EntityXfRecordProcess entityXfRecordProcess = xfRecordProcessService.selectTradeNo(request.getCompanyId(), entityXfGoodsListProcess.getOrderNo(), null);
//        if (entityXfRecordProcess == null) {
//            return ResultUtil.error(ResultEnum.Err_805);
//        }
//
//        if (entityXfRecordProcess.getVerification() == 1) {
//            return ResultUtil.error(ResultEnum.Err_2041);
//        }

        entityXfRecordProcess.setId(null);
        entityXfRecordProcess.setOrderNo("HX"+entityXfRecordProcess.getOrderNo());
        entityXfRecordProcess.setDeviceNo(request.getMachNo());
        entityXfRecordProcess.setDeptName(deviceInfoVo.getDeviceName());
        entityXfRecordProcess.setConsState(4);
        entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(new Date(),"yyyyMM"));
        entityXfRecordProcess.setConsTime(new Date());
        entityXfRecordProcess.setCreateTime(new Date());
        xfRecordProcessService.insertEntityXfRecord(entityXfRecordProcess.getComId(),entityXfRecordProcess);

        xfRecordProcessService.verificationEntityXfRecord(request.getCompanyId(), orderNoV);
        //迁移成功库
        MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
        mqSaveOrderVo.setComId(request.getCompanyId());
        mqSaveOrderVo.setId(entityXfRecordProcess.getId());
        mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
        saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

        try {
            //改原订单
            XfOrderVerificationRequest xfOrderVerificationRequest = new XfOrderVerificationRequest();
            xfOrderVerificationRequest.setCompanyId(request.getCompanyId());
            xfOrderVerificationRequest.setOrderNo(orderNoV);
            xfOrderVerificationRequest.setMonthValue(monthVv);
            xfOrderVerificationRequest.setMachNo(request.getMachNo());
            xfOrderVerificationRequest.setMachName(deviceInfoVo.getDeviceName());
            xfRecordFeign.orderVerification(xfOrderVerificationRequest);
        }catch (Exception e){
            log.error("更改异常 6YWl4hXV 【{}】",e);
        }


        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("mealDate", dateOrder);
        orderMap.put("mealNo", mealNo);
        List<EntityXfMealTime> mealTimeList = xfMealTimeService.getMealInfo(request.getCompanyId());
        if (mealTimeList.size() > 0) {
            for (EntityXfMealTime entityXfMealTime : mealTimeList) {
                if (entityXfMealTime.getMealNo().equals(mealNo.toString())) {
                    orderMap.put("mealName", entityXfMealTime.getMealName());
                    break;
                }
            }
        }

        orderMap.put("address", "");

        Map<String, Object> accountMap = new HashMap<>();
        accountMap.put("name", entityPersonnelInfo.getPName());
        accountMap.put("money", entityXfAccountInfo.getAccountRechargeMoney());
        accountMap.put("allowance", entityXfAccountInfo.getAccountSubsidyMoney());
        if (entityCardInfo != null) {
            accountMap.put("expireDate", DateUtils.getStrDate(entityCardInfo.getEndDate(), DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        accountMap.put("cardtype", entityXfAccountInfo.getAccTypeId());

        resMap.put("dishes", entityXfGoodsListProcess1);
        resMap.put("order", orderMap);
        resMap.put("accountInf", accountMap);

        return ResultUtil.success(resMap);
    }


}
